package com.jwt.spring.user.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.jwt.actions.JWTActions;
import com.jwt.dao.bean.Account;
import com.jwt.spring.login.session.UserSession;

public class SignonController implements Controller {

	private JWTActions jwtActions;

	

	/**
	 * @param jwtActions the jwtActions to set
	 */
	public void setJwtActions(JWTActions jwtActions) {
		this.jwtActions = jwtActions;
	}



	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Account account = this.jwtActions.getAccount(username, password);
		if (account == null) {
			return new ModelAndView("main", "message",
					"Invalid username or password.");
		} else {
			UserSession userSession = new UserSession(account);
			request.getSession().setAttribute("userSession", userSession);
			String forwardAction = request.getParameter("forwardAction");
			if (forwardAction != null) {
				response.sendRedirect(forwardAction);
				return null;
			} else {
				return new ModelAndView("jwt");
			}
		}
	}

}
